<template>
  <el-tabs 
    v-model="activeView" 
    type="card"
    :closable="viewTabs.length > 1" 
    @tab-click="handleTabClick"
    @tab-remove="handleTabRemove"
    class="view-tab">
    <el-tab-pane
      :key="item.name"
      v-for="item in viewTabs"
      :label="item.label"
      :name="item.name">
    </el-tab-pane>
  </el-tabs>
</template>

<script>
  export default {
    data() {
      return {
        history: []
      }
    },
    computed: {
      viewTabs() {
        return this.$store.state.RouterCache.cacheViewObjList
      },
      //当前激活的路由
      activeView: {
        get() {
          return this.$store.state.RouterCache.activeViewPath
        },
        set(name) {
          this.$store.commit('RouterCache/setActiveViewName', name)
        }
      }
    },
    mounted() {
      this.history.push(this.$route.path)
      this.$watch('$route', ()=> {
        this.history.push(this.$route.path)
      })
    },
    methods: {
      handleTabClick(tab) {
        this.$router.push(this.viewTabs[tab.index].path)
      },
      handleTabRemove(name) {
        const tabs = JSON.parse(JSON.stringify(this.viewTabs));
        const preHistory = this.history[this.history.length-2];
        const preTab = tabs.find((item)=> {
          return item.path === preHistory;
        })

        this.$store.commit('RouterCache/deleteCacheView', name);
        
        if (this.activeView === name) {
          if (preTab) {
             this.$router.back()
          } else {
            this.$router.push(tabs[0].path)
          }
        }
      }
    },
  }
</script>

<style scoped lang="scss">
  .view-tab /deep/ {
    .el-tabs__header {
      margin: 0;
      border: none
    }
    .el-tabs__nav {
      border: none;
    }
    .el-tabs__item {
      border: 1px solid #DDD;
      &:first-child {
        border: 1px solid #DDD;
      }
      margin: 2px 5px 2px 0;
      height: 30px;
      line-height: 30px;
      border-radius: 3px;
      &.is-active {
        border-color: $color-primary;
      }
    }
    .el-tabs__nav-next, .el-tabs__nav-prev {
      line-height: 30px;
    }
  }
</style>